package com.iscas.lndicatormonitor.config;

import com.iscas.lndicatormonitor.filter.CustomAuthorizationFilter;
import com.iscas.lndicatormonitor.filter.JwtRequestFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

@EnableWebSecurity
@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private JwtRequestFilter jwtRequestFilter;
    @Autowired
    private CustomAuthorizationFilter customAuthorizationFilter;
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()
                .cors().configurationSource(corsConfigurationSource()) // 启用 CORS 并应用配置
                .and()
                .csrf().disable()
                .authorizeRequests()
                .antMatchers("/user/login","/user/logout","/record/getRecordById").permitAll() // 排除登录接口
                .anyRequest().authenticated() // 其他所有请求都需要验证
                .and()
                // 在 UsernamePasswordAuthenticationFilter 之前添加 jwtRequestFilter
                .addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class)
                // 在 jwtRequestFilter 之后添加 CustomAuthorizationFilter
                .addFilterAfter(customAuthorizationFilter, jwtRequestFilter.getClass())
                .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS);
    }
    @Bean
    public CorsConfigurationSource corsConfigurationSource() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(true);
        config.addAllowedOriginPattern("*"); // 允许所有源
        config.addAllowedHeader("*"); // 允许所有头
        config.addAllowedMethod("*"); // 允许所有方法
        config.setMaxAge(3600L); // 预检请求的有效期
        source.registerCorsConfiguration("/**", config);
        return source;
    }
}